﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MaguenBrokersMVC.Models;
using System.Net;
using System.Net.Mail;

namespace MaguenBrokersMVC.Controllers
{
    public class SeguroVehiculoController : Controller
    {
        private readonly MaguenDb db = new MaguenDb();

        [HttpGet]
        public ActionResult AjaxGetModelos(int idVehiculoTipo = 0, int idVehiculoMarca = 0)
        {
            var departamentos = db.VehiculoModelos.Where(
                v => v.VehiculoMarca.Id == idVehiculoMarca && v.VehiculoTipo.Id == idVehiculoTipo)
            .Distinct()
            .OrderBy(x => x.Nombre)
            .AsEnumerable()
            .Select(x => new SelectListItem
            {
                Text = x.Nombre,
                Value = x.Id.ToString(CultureInfo.InvariantCulture)
            });
            return Json(departamentos, JsonRequestBehavior.AllowGet);
        }

        private bool EnviarEmail(SeguroVehiculo seguroVehiculo)
        {
            var tipoVehiculo = db.VehiculoTipos.Single(x => x.Id == seguroVehiculo.VehiculoTipoId);
            var marcaVehiculo = db.VehiculoMarcas.Single(x => x.Id == seguroVehiculo.VehiculoMarcaId);
            var modeloVehiculo = db.VehiculoModelos.Single(x => x.Id == seguroVehiculo.VehiculoModeloId);
            

            var emMailMessage = new MailMessage();

            emMailMessage.To.Add(new MailAddress("leandro@skidelsky.com.ar"));

            emMailMessage.From = new MailAddress(seguroVehiculo.Email);

            emMailMessage.Subject = "Requerimiento Pagina Web Seguro de Vehiculo";

            emMailMessage.Body =
                "Hola Leandro, has recibido un requerimiento de un clinte, a continuación están los detalles. " +
                "\n " +
                "Apellido y nombre: " + seguroVehiculo.Apellido + " " + seguroVehiculo.Nombre +
                "\n " +
                "Email: " + seguroVehiculo.Email +
                "\n " +
                "Telefonoa: " + seguroVehiculo.Telefono +
                "\n " +
                "Tpo de Vehiculo: " + tipoVehiculo.Nombre +
                "\n " +
                "Marca: " + marcaVehiculo.Nombre +
                "\n " +
                "Modelo: " + modeloVehiculo.Nombre +
                "\n " +
                "Combustible: " + seguroVehiculo.Combustible +
                "\n " +
                "Año: " + seguroVehiculo.Año;


            emMailMessage.IsBodyHtml = false;

            emMailMessage.Priority = MailPriority.High;

            var emMailMessage2 = new MailMessage();

            emMailMessage2.To.Add(new MailAddress(seguroVehiculo.Email));

            emMailMessage2.From = new MailAddress(seguroVehiculo.Email);

            emMailMessage2.Subject = "Requerimiento Pagina Web Seguro de Vehiculo";

            emMailMessage2.Body = "Hola " + seguroVehiculo.Nombre + ", Gracias por contactarte con Maguen Brokers Asesores de Seguros, tu cotización se está presupuestando, a la brevedad nos contactaremos contigo. ";

            emMailMessage2.IsBodyHtml = false;

            emMailMessage2.Priority = MailPriority.High;

            var smtpClient = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                Credentials =
                    new NetworkCredential("vidadigital.chaco.info@gmail.com", "vidadigital.chaco"),
                EnableSsl = true
            };

            try
            {
                smtpClient.Send(emMailMessage);
                smtpClient.Send(emMailMessage2);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        [HttpPost]
        public ActionResult CotizarPartial(SeguroVehiculo seguroVehiculo)
        {
            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", 1);
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", 1);
            if (ModelState.IsValid)
            {
                try
                {
                    db.SeguroVehiculos.Add(seguroVehiculo);
                    db.SaveChanges();
                    if (EnviarEmail(seguroVehiculo))
                    {
                        ViewBag.Message = "Operación exitosa. En breve nos comunicaremos con Ud.";
                        ViewBag.Color = "Green";
                    }
                    else
                    {
                        ViewBag.Message = "No se pudo enviar el correo electrónico.";
                        ViewBag.Color = "Red";
                    }
                    ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", 1);
                    ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", 1);
                    ViewBag.VehiculoModeloId = new SelectList(new List<VehiculoModelo>(), "Id", "Nombre");
                    return PartialView("_Cotizar");

                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR!";
                    ViewBag.Color = "Red";
                    return PartialView("_Cotizar", new SeguroHogar { });
                }
            }
            return PartialView("_Cotizar", seguroVehiculo);
        }

        [ChildActionOnly]
        public ActionResult CotizarPartial()
        {
            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", 1);
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", 1);
            ViewBag.VehiculoModeloId = new SelectList(new List<VehiculoModelo>(), "Id", "Nombre");
            return PartialView("_Cotizar");
        }
        public ViewResult Principal()
        {
            return View();
        }
        //
        // GET: /SeguroVehiculo/
        [Authorize]
        public ViewResult Index()
        {
            var segurovehiculos = db.SeguroVehiculos.Include(s => s.VehiculoTipo).Include(s => s.VehiculoMarca).Include(s => s.VehiculoModelo);
            return View(segurovehiculos.ToList());
        }

        //
        // GET: /SeguroVehiculo/Details/5
        [Authorize]
        public ViewResult Details(int id)
        {
            SeguroVehiculo segurovehiculo = db.SeguroVehiculos.Find(id);
            return View(segurovehiculo);
        }

        //
        // GET: /SeguroVehiculo/Create
        [Authorize]
        public ActionResult Create()
        {
            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre");
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre");
            ViewBag.VehiculoModeloId = new SelectList(db.VehiculoModelos, "Id", "Nombre");
            return View();
        }

        //
        // POST: /SeguroVehiculo/Create
        [Authorize]
        [HttpPost]
        public ActionResult Create(SeguroVehiculo segurovehiculo)
        {
            if (ModelState.IsValid)
            {
                db.SeguroVehiculos.Add(segurovehiculo);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", segurovehiculo.VehiculoTipoId);
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", segurovehiculo.VehiculoMarcaId);
            ViewBag.VehiculoModeloId = new SelectList(db.VehiculoModelos, "Id", "Nombre", segurovehiculo.VehiculoModeloId);
            return View(segurovehiculo);
        }

        //
        // GET: /SeguroVehiculo/Edit/5
        [Authorize]
        public ActionResult Edit(int id)
        {
            SeguroVehiculo segurovehiculo = db.SeguroVehiculos.Find(id);
            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", segurovehiculo.VehiculoTipoId);
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", segurovehiculo.VehiculoMarcaId);
            ViewBag.VehiculoModeloId = new SelectList(db.VehiculoModelos, "Id", "Nombre", segurovehiculo.VehiculoModeloId);
            return View(segurovehiculo);
        }

        //
        // POST: /SeguroVehiculo/Edit/5
        [Authorize]
        [HttpPost]
        public ActionResult Edit(SeguroVehiculo segurovehiculo)
        {
            if (ModelState.IsValid)
            {
                db.Entry(segurovehiculo).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.VehiculoTipoId = new SelectList(db.VehiculoTipos, "Id", "Nombre", segurovehiculo.VehiculoTipoId);
            ViewBag.VehiculoMarcaId = new SelectList(db.VehiculoMarcas, "Id", "Nombre", segurovehiculo.VehiculoMarcaId);
            ViewBag.VehiculoModeloId = new SelectList(db.VehiculoModelos, "Id", "Nombre", segurovehiculo.VehiculoModeloId);
            return View(segurovehiculo);
        }

        //
        // GET: /SeguroVehiculo/Delete/5
        [Authorize]
        public ActionResult Delete(int id)
        {
            SeguroVehiculo segurovehiculo = db.SeguroVehiculos.Find(id);
            return View(segurovehiculo);
        }

        //
        // POST: /SeguroVehiculo/Delete/5
        [Authorize]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            SeguroVehiculo segurovehiculo = db.SeguroVehiculos.Find(id);
            db.SeguroVehiculos.Remove(segurovehiculo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}